<template>
	<view>
		<u-notify ref="uNotify"></u-notify>
		<u-collapse ref='coll' :value="['1','2']">
			<u-collapse-item name="1" title="基本信息" icon="https://project.gxrunxiang.com/cdn/my.png">
				<u-form ref="uForm" :rules="rules" label-width="auto" :model="orderdetail">
					<u-form-item label="所在部门"　:required="true" name="OrderDept" prop="OrderDept"><u-input v-model="orderdetail.OrderDept"/></u-form-item>
					<u-form-item label="工单编号"><u-input v-model="orderdetail.No" disabledColor="#ffffff" disabled placeholder="系统自动生成"/></u-form-item>
					<u-form-item label="网络类型" @click="showNetType = true;"　:required="true" name="NetType" prop="NetType"><u-input v-model="orderdetail.NetType"  disabledColor="#ffffff" disabled /></u-form-item>
					<u-form-item label="接单时间" @click="showAcc = true; "　:required="true" name="AcceptanceTime" prop="AcceptanceTime"><u--input　v-model="orderdetail.AcceptanceTime" disabledColor="#ffffff" disabled /></u-form-item>
					<u-form-item label="完工时间" @click="showFinish = true; "　:required="true" name="FinishTime" prop="FinishTime"><u--input　v-model="orderdetail.FinishTime" disabledColor="#ffffff" disabled /></u-form-item>
					<!-- <u-form-item label="县"><u-input v-model="orderdetail.Town" /></u-form-item> -->
					<u-form-item label="部门"　:required="true" name="Dept" prop="Dept"><u-input v-model="orderdetail.Dept" /></u-form-item>
					<u-form-item label="辖区"　:required="true" name="District" prop="District"><u-input v-model="orderdetail.District" /></u-form-item>
					<u-form-item label="工单来源" @click="showSource = true;"　:required="true" name="Source" prop="Source"><u-input v-model="orderdetail.Source" disabledColor="#ffffff" disabled/></u-form-item>
					<u-form-item label="故障地址"　:required="true" name="Address" prop="Address"><u-input v-model="orderdetail.Address" /></u-form-item>
					<u-form-item label="故障描述"　:required="true" name="Content" prop="Content"><u--textarea v-model="orderdetail.Content" placeholder="请输入内容"
							height="180" maxlength="300"></u--textarea></u-form-item>
					<u-form-item label="维护类型"　:required="true" name="FaultType" prop="FaultType" @click="showFaultType = true"><u-input v-model="orderdetail.FaultType" disabledColor="#ffffff" disabled/></u-form-item>
					<u-form-item label="工单类型"　:required="true" name="OrderType" prop="OrderType" @click="showOrderType = true"><u-input v-model="orderdetail.OrderType" disabledColor="#ffffff" disabled/></u-form-item>
					<u-form-item label="派单部门"　:required="true" name="SendOrderDept" prop="SendOrderDept"><u-input v-model="orderdetail.SendOrderDept" /></u-form-item>
					<u-form-item label="派单人"　:required="true" name="SendOrderManName" prop="SendOrderManName"><u-input v-model="orderdetail.SendOrderManName" /></u-form-item>
					<u-form-item label="润象接单人"　:required="true" name="ReceiveOrderManName" prop="ReceiveOrderManName"><u-input v-model="orderdetail.ReceiveOrderManName" /></u-form-item>
					<u-form-item label="标准地址" :required="true"  @click="showAddress = true"><u-input disabledColor="#ffffff" disabled /></u-form-item>
					<u-button @click="toChoose">添加地址</u-button>
					<u--text v-for="item in standardAddrList" margin="0 0 8px 0" type="info" :text="item.addr" @click='delAddr(item)'></u--text>
					<u--text margin="0 0 8px 0" type="info" prefixIcon="map" :text="orderdetail.Lat + ',' + orderdetail.Lng">
					</u--text>
					<u-popup :show="showAddress" title="请选择标准地址" @close="showAddress = false">
						<u-search placeholder="多个关键词请用空格隔开" v-model="keyword" @custom="selectAddr" @search="selectAddr"></u-search>
						<u-list height='460px' @scrolltolower="scrolltolower">
							<u-list-item v-for="(item, index) in addrlist" :key="index">
								<u-cell :title='item.FullName' @click="changeAddr(item.FullName,item.AddrCode)">
								</u-cell>
							</u-list-item>
							<u-loadmore :status="addrStatus" v-if="addrLoading" />
						</u-list>
					</u-popup>
					<u-datetime-picker
					  :show="showAcc"
					  @cancel="showAcc = false"
					  @confirm="changeAccTime" :closeOnClickOverlay="true" @close="showAcc = false"
					  mode="date"
					  v-model="value1"
					  :minDate="1704038400000"
					></u-datetime-picker>
					<u-datetime-picker
					  :show="showFinish"
					  @cancel="showFinish = false"
					  @confirm="changeFinishTime" :closeOnClickOverlay="true" @close="showFinish = false"
					  mode="date"
					  v-model="value2"
					  :minDate="1704038400000"
					></u-datetime-picker>
					<u-action-sheet	 :show="showNetType" :actions="dicNetType" title="请选择网络类型" @close="showNetType = false" @select="netTypeSelect" >
					</u-action-sheet>
					<u-action-sheet	 :show="showSource" :actions="dicSource" title="请选择工单来源" @close="showSource = false" @select="sourceSelect" >
					</u-action-sheet>
					<u-action-sheet	 :show="showFaultType" :actions="dicFaultType" title="请选择维护类型" @close="showFaultType = false" @select="faultTypeSelect" >
					</u-action-sheet>
					<u-action-sheet	 :show="showOrderType" :actions="dicOrderType" title="请选择工单类型" @close="showOrderType = false" @select="orderTypeSelect" >
					</u-action-sheet>
				</u-form>
			</u-collapse-item>
			<u-collapse-item name="1" title="派单截图" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					itype='派单截图' :sizeType='["compressed"]' :maxCount="10"></u-upload>
			</u-collapse-item>
		</u-collapse>
		<u-button @click="submit">提交</u-button>
	</view>
</template>
<script>
	import {
		baseUrl,
	} from '@/common/config.js'
	import {
		mapGetters
	} from 'vuex'

	import {
		addorder,
		GetListByParent,
		getaddrslist,
		GetAddrByLatlng
	} from '@/common/api.js'
	export default {
		data() {
			return {
				itypelist: {
					"1": "派单截图",
				},
				orderdetail: {
					Lng: "",
					Lat: "",
					OrderDept: "",
					NetType: "",
					AcceptanceTime: "",
					FinishTime: "",
					Dept: "",
					District: "",
					Source: "",
					Address: "",
					Content: "",
					FaultType: "",
					SendOrderDept: "",
					SendOrderManName: "",
					ReceiveOrderManName: "",
					StandardAddress: "",
					AddrCodes: "",
					OrderType:""
				},
				fileList1: [],
				fileList2: [],
				token: "",
				addrStatus: 'loadmore',
				dicCity: [],
				showFtype: false,
				showAcc: false,
				showFinish: false,
				showAddress: false,
				addrLoading: false,
				showNetType: false,
				showSource: false,
				showFaultType: false,
				showOrderType: false,
				value1: Number(new Date()),
				value2: Number(new Date()),
				user: {},
				keyword: "",
				addrlist:{},
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				totalPage: "", //总页数
				total: 0, //数据总数
				status: 'loadmore', //加载状态
				standardAddrList: [], //标准地址的列表
				dicNetType:[
					{
						name: "城网",
						value: "城网"
					},{
						name: "农网",
						value: "农网"
				}],
				dicSource:[
					{
						name: "网络公司微信派单",
						value: "网络公司微信派单"
					},{
						name: "项目部自主发现",
						value: "项目部自主发现"
					},{
						name: "其它",
						value: "其它"
				}],
				dicFaultType:[
					{
						name: "自维",
						value: "自维"
					},{
						name: "代维",
						value: "代维"
				}],
				dicOrderType:[
					{
						name: "故障工单",
						value: "故障工单"
					},{
						name: "优化工单",
						value: "优化工单"
					},{
						name: "其它工单",
						value: "其它工单"
				}],
				ErrorData: {
					message: '请提交派单截图!',
					type: 'error',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 2000,
					safeAreaInsetTop: false
				},
				ErrorNotify: {
					message: '请选择标准地址!',
					type: 'error',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 2000,
					safeAreaInsetTop: false
				},
				rules: {
					'OrderDept': {
						required: true,
						message: '请输入所在部门',
						trigger: ['blur']
					},
					'NetType': {
						required: true,
						message: '请输入网络类型',
						trigger: ['blur']
					},
					'AcceptanceTime': {
						required: true,
						message: '请输入接单日期',
						trigger: ['blur']
					},
					'FinishTime': {
						required: true,
						message: '请输入完工时间',
						trigger: ['blur']
					},
					'Dept': {
						required: true,
						message: '请输入部门',
						trigger: ['blur']
					},
					'District': {
						required: true,
						message: '请输入辖区',
						trigger: ['blur']
					},
					'Source': {
						required: true,
						message: '请输入工单来源',
						trigger: ['blur']
					},
					'Address': {
						required: true,
						message: '请选择故障地址',
						trigger: ['blur']
					},
					'Content': {
						required: true,
						message: '请输入故障描述',
						trigger: ['blur']
					},
					'FaultType': {
						required: true,
						message: '请输入维护类型',
						trigger: ['blur']
					},
					'SendOrderDept': {
						required: true,
						message: '请输入派单部门',
						trigger: ['blur']
					},
					'SendOrderManName': {
						required: true,
						message: '请输入派单人',
						trigger: ['blur']
					},
					'ReceiveOrderManName': {
						required: true,
						message: '请输入润象接单人',
						trigger: ['blur']
					},
				},
			}
		},
		onLoad() {
			this.token = uni.getStorageSync("$token")
			uni.getLocation({
				type: 'wgs84',
				geocode: true, //设置该参数为true可直接获取经纬度及城市信息
				success: (res) => {
					console.log("定位结果" + res.longitude + "，" + res.latitude)
					this.orderdetail.Lng = res.longitude;
					this.orderdetail.Lat = res.latitude
					this.loading = false
					GetAddrByLatlng(res.latitude+ "," + res.longitude).then(res => {
						var arr = res.split(",")
						this.orderdetail.Address = arr[2];
					})
				},
				fail: () => {
					// this.outcenter = [111.11111, 11.111111]
					// console.log("定位结果失败")
					// console.log(this)
					uni.showToast({
						title: '获取地址失败，将导致部分功能不可用',
						icon: 'none'
					});
				}
			});
		},
		onShow() {
			let user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.user = user
			this.orderdetail.OrderDept = user.DeptName
			this.orderdetail.Dept = user.DeptName
			this.orderdetail.District = user.DeptName
			this.standardAddrList = []
			for(let i = 0;i<getApp().globalData.choosenAddrId.length;i++){
				this.standardAddrList[i] = {
					code: getApp().globalData.choosenAddrId[i],
					addr: getApp().globalData.choosenAddrName[i]
				}
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		    this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.orderdetail.Id||this.user.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			submit() {
				if(this.standardAddrList.length == 0){
					this.$refs.uNotify.show(this.ErrorNotify)
					return;
				}
				if (this.fileList1.length == 0) {
					this.$refs.uNotify.show(this.ErrorData)
				} else {
				this.$refs.uForm.validate().then(res => {
						this.standardAddrList.forEach(e=>{
							this.orderdetail.AddrCodes = this.orderdetail.AddrCodes + ',' + e.code
							this.orderdetail.StandardAddress = this.orderdetail.StandardAddress + ',' + e.addr
						})
						getApp().globalData.choosenAddrId = []
						getApp().globalData.choosenAddrName = []
							addorder(this.orderdetail).then((res) => {
								if (res === true) {
									uni.navigateBack()
								}
							})
						
						// else{
						// 	workerupdate(this.buildworkerinfo).then((res) => {
						// 		if (res === true) {
						// 			uni.redirectTo({
						// 				url: 'buildworkerinfo'
						// 			})
						// 		}
						// 	})
						// }
						
					}).catch(errors => {
						console.log(errors);
						uni.$u.toast('请填写必填参数！')
					})	
				}
			},
			changeAccTime(e){
				const timeFormat = uni.$u.timeFormat
				this.orderdetail.AcceptanceTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				this.showAcc = false
			},
			changeFinishTime(e){
				const timeFormat = uni.$u.timeFormat
				this.orderdetail.FinishTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				this.showFinish = false
			},
			selectAddr(){
				this.addrlist = [];
				this.pageIndex = 1;
				this.addrLoading = true
				this.getaddrlist()
			},
			async getaddrlist(){
				let para = {}
				para.OrderBys = ['Id desc'];
				para.pageSize = this.pageSize;
				para.pageIndex = this.pageIndex;
				para.Parameters = [];
				var selcets = this.keyword.split(' ');
				for(let i = 0;i < selcets.length;i++){
					if(selcets[i].length > 0)
					para.Parameters.push({
					   	FieldName: "FullName",
					   	ConditionalType: "Like",
					   	FieldValue: selcets[i]
					   })
				}
				await getaddrslist(para).then(res => {
					this.addrlist.push(...res.data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.addrlist.length < this.pageSize) {
					this.addrLoading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.addrStatus = 'nomore';
				}else {
					this.addrStatus = 'loadmore';
				}
			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.addrStatus = 'nomore';
					return;
				};
				this.addrStatus = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getaddrlist(); //修改页数后，重新获取数据
			},
			changeAddr(e,c){
				this.showAddress = false;
				const toggleArrayValue = (arr, value) => {
				  // 检查是否存在（使用严格相等判断）
				  const index = arr.findIndex(item => item === value);
				  // 存在则删除，不存在则添加
				  return index === -1 
					? [...arr, value] 
					: arr.filter((_, i) => i !== index);
				};
				getApp().globalData.choosenAddrId = toggleArrayValue(getApp().globalData.choosenAddrId,c)
				getApp().globalData.choosenAddrName = toggleArrayValue(getApp().globalData.choosenAddrName,e)
				for(let i = 0;i<getApp().globalData.choosenAddrId.length;i++){
					this.standardAddrList[i] = {
						code: getApp().globalData.choosenAddrId[i],
						addr: getApp().globalData.choosenAddrName[i]
					}
				}
				// if(this.orderdetail.StandardAddress == ""){
				// 	this.orderdetail.StandardAddress = e
				// }else{
				// 	this.orderdetail.StandardAddress = this.orderdetail.StandardAddress + ',' + e
				// }
				// if(this.orderdetail.AddrCodes == ""){
				// 	this.orderdetail.AddrCodes = c
				// }else{
				// 	this.orderdetail.AddrCodes = this.orderdetail.AddrCodes + ',' + c
				// }
				// let arr = this.orderdetail.StandardAddress.split(',')
				// for(let i = 0;i<arr.length;i++){
				// 	this.standardAddrList[i] = {
				// 		code: this.orderdetail.AddrCodes.split(',')[i],
				// 		addr: arr[i]
				// 	}
				// }
			},
			delAddr(e){
				// if(this.standardAddrList.length == 1){
				// 	this.standardAddrList = []
				// 	this.orderdetail.StandardAddress = ""
				// 	this.orderdetail.AddrCodes = ""
				// }else{
				// 	this.standardAddrList = []
				// 	this.orderdetail.StandardAddress = this.orderdetail.StandardAddress.split("," + e.addr).join("")
				// 	this.orderdetail.AddrCodes = this.orderdetail.AddrCodes.split("," + e.code).join("")
				// 	let arr = this.orderdetail.StandardAddress.split(',')
				// 	for(let i = 0;i<arr.length;i++){
				// 		this.standardAddrList[i] = {
				// 			code: this.orderdetail.AddrCodes.split(',')[i],
				// 			addr: arr[i]
				// 		}
				// 	}
				// }
				// console.log(this.orderdetail)
				var idList = getApp().globalData.choosenAddrId
				var nameList = getApp().globalData.choosenAddrName
				var idIndex = idList.findIndex(item => item === e.code);
				var nameIndex = nameList.findIndex(item => item === e.addr);
				getApp().globalData.choosenAddrId = idList.filter((_, i) => i !== idIndex)
				getApp().globalData.choosenAddrName = nameList.filter((_, i) => i !== nameIndex)
				this.standardAddrList = []
				for(let i = 0;i<getApp().globalData.choosenAddrId.length;i++){
					this.standardAddrList[i] = {
						code: getApp().globalData.choosenAddrId[i],
						addr: getApp().globalData.choosenAddrName[i]
					}
				}
			},
			netTypeSelect(e) {
				this.orderdetail.NetType = e.name
			},
			sourceSelect(e){
				this.orderdetail.Source = e.name
			},
			faultTypeSelect(e){
				this.orderdetail.FaultType = e.name
			},
			orderTypeSelect(e){
				this.orderdetail.OrderType = e.name
			},
			toChoose(){
				uni.navigateTo({
					url: "address?level=0&backto=1"
				})
			}
		}
	}
</script>